package com.koron.order.LineHomepage.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.koron.bean.base.Response;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.order.LineHomepage.bean.VO.ReportGenerationVO;
import com.koron.order.LineHomepage.bean.converter.LineOperationConverter;
import com.koron.order.LineHomepage.bean.excel.LineOperationReportExcel;
import com.koron.order.LineHomepage.bean.excel.StyleUtills;
import com.koron.order.LineHomepage.bean.query.LineOperationAnalysisQuery;
import com.koron.order.LineHomepage.service.LineOperationAnalysisService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.koron.ebs.mybatis.ADOConnection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName: LineOperationAnalysisController
 * @Description:
 * @Date: 2023/2/15
 * @Author: 李一辰
 * @Version: 1.0
 **/
@Slf4j
@RestController
@RequestMapping("/lineOperationAnalysisController")
@Api(tags ="线路运行分析报告")
public class LineOperationAnalysisController {


    @Autowired
    private LineOperationAnalysisService lineOperationAnalysisService;
    @Autowired
    private LineOperationConverter lineOperationConverter;

    private String getCurrDs() {
        return ThreadLocalContext.get().getCurrDs();
    }
    @ApiOperation("线路运行分析报告自动生成")
    @PostMapping("/reportGeneration")
    public Response<List<ReportGenerationVO>> reportGeneration(LineOperationAnalysisQuery analysisQuery,@RequestBody List<ReportGenerationVO> reportGenerationData){
        List<ReportGenerationVO> reportGeneration = ADOConnection.runTask(getCurrDs(), lineOperationAnalysisService, "reportGeneration", List.class, analysisQuery);
        for (ReportGenerationVO reportGenerationDatum : reportGenerationData) {
            String equipmentName = reportGenerationDatum.getEquipmentName();
            ReportGenerationVO goal = reportGeneration.stream().filter(i -> i.getEquipmentName().equals(equipmentName)).findFirst().orElse(new ReportGenerationVO());
            goal.setEquipmentName(equipmentName);
            goal.setEquipmentId(reportGenerationDatum.getEquipmentId());
            goal.setLineCut(reportGenerationDatum.getLineCut());
            goal.setLineNonCut(reportGenerationDatum.getLineNonCut());
            goal.setLineTotal(reportGenerationDatum.getLineTotal());
            goal.setEvaluate(reportGenerationDatum.getEvaluate());
            goal.setRemark(reportGenerationDatum.getRemark());
        }

        List<ReportGenerationVO> list = ADOConnection.runTask(getCurrDs(), lineOperationAnalysisService, "insertBatch", List.class, reportGeneration);
        return Response.ok(list);
    }
//    @ApiOperation("生成报告")
//    @PostMapping("/insertBatch")
    public Response<List<ReportGenerationVO>>insertBatch(@RequestBody List<ReportGenerationVO> reportGenerationVO){
        List<ReportGenerationVO> list = ADOConnection.runTask(getCurrDs(), lineOperationAnalysisService, "insertBatch", List.class, reportGenerationVO);
        return Response.ok(list);
    }
    @ApiOperation("查看报告")
    @GetMapping("/selectList")
    public Response<List<ReportGenerationVO>> selectList(@RequestParam(name = "date",required = false) Date date ,
                                                         @RequestParam(name = "equipmentNames",required = false)List<String> equipmentNames){
        if(date == null){
            date = new Date();
        }
        List<ReportGenerationVO> selectList = ADOConnection.runTask(getCurrDs(), lineOperationAnalysisService, "selectList", List.class, date,equipmentNames);
        ReportGenerationVO reportGenerationVO = new ReportGenerationVO();
        reportGenerationVO.setLineTotal(selectList.stream().filter(i->i.getLineTotal()!=null&&i.getLineTotal()!=0).mapToInt(ReportGenerationVO::getLineTotal).sum());
        reportGenerationVO.setLineCut(selectList.stream().filter(i->i.getLineCut()!=null&&i.getLineCut()!=0).mapToInt(ReportGenerationVO::getLineCut).sum());
        reportGenerationVO.setLineNonCut(selectList.stream().filter(i->i.getLineNonCut()!=null&&i.getLineNonCut()!=0).mapToInt(ReportGenerationVO::getLineNonCut).sum());
        reportGenerationVO.setDefectNew(selectList.stream().filter(i->i.getDefectNew()!=null&&i.getDefectNew()!=0).mapToInt(ReportGenerationVO::getDefectNew).sum());
        reportGenerationVO.setDefect00(selectList.stream().filter(i->i.getDefect00()!=null&&i.getDefect00()!=0).mapToInt(ReportGenerationVO::getDefect00).sum());
        reportGenerationVO.setDefect01(selectList.stream().filter(i->i.getDefect01()!=null &&i.getDefect01()!=0).mapToInt(ReportGenerationVO::getDefect01).sum());
        reportGenerationVO.setDefect01New(selectList.stream().filter(i->i.getDefect01New()!=null &&i.getDefect01New()!=0).mapToInt(ReportGenerationVO::getDefect01New).sum());
        reportGenerationVO.setDefect00New(selectList.stream().filter(i->i.getDefect00New()!=null &&i.getDefect00New()!=0).mapToInt(ReportGenerationVO::getDefect00New).sum());
        reportGenerationVO.setDefectTotal(selectList.stream().filter(i->i.getDefectTotal()!=null &&i.getDefectTotal()!=0).mapToInt(ReportGenerationVO::getDefectTotal).sum());
        reportGenerationVO.setDefectLast00(selectList.stream().filter(i->i.getDefectLast00()!=null &&i.getDefectLast00()!=0).mapToInt(ReportGenerationVO::getDefectLast00).sum());
        reportGenerationVO.setDefectLast01(selectList.stream().filter(i->i.getDefectLast01()!=null &&i.getDefectLast01()!=0).mapToInt(ReportGenerationVO::getDefectLast01).sum());
        reportGenerationVO.setDefectTotalLast(selectList.stream().filter(i->i.getDefectTotalLast()!=null &&i.getDefectTotalLast()!=0).mapToInt(ReportGenerationVO::getDefectTotalLast).sum());
        reportGenerationVO.setDefectThis01(selectList.stream().filter(i->i.getDefectThis01()!=null &&i.getDefectThis01()!=0).mapToInt(ReportGenerationVO::getDefectThis01).sum());
        reportGenerationVO.setDefectThis00(selectList.stream().filter(i->i.getDefectThis00()!=null &&i.getDefectThis00()!=0).mapToInt(ReportGenerationVO::getDefectThis00).sum());
        reportGenerationVO.setDefectTotalThis(selectList.stream().filter(i->i.getDefectTotalThis()!=null &&i.getDefectTotalThis()!=0).mapToInt(ReportGenerationVO::getDefectTotalThis).sum());
        reportGenerationVO.setTripTimes(selectList.stream().filter(i->i.getTripTimes()!=null &&i.getTripTimes()!=0).mapToInt(ReportGenerationVO::getTripTimes).sum());
        reportGenerationVO.setEquipmentName("总计");
        selectList.add(reportGenerationVO);
        return  Response.ok(selectList);
    }

    @SneakyThrows
    @ApiOperation("导出报告")
    @GetMapping("/export")
    public void export(HttpServletResponse response,
                       @RequestParam(name = "date",required = false) Date date ,
                       @RequestParam(name = "equipmentNames",required = false)List<String> equipmentNames){
        String path = "excel/lineOperationReport_export.xlsx";
        ClassPathResource classPathResource = new ClassPathResource(path);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("线路运行分析报告", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        if(date == null){
            date = new Date();
        }
        List<ReportGenerationVO> selectList = ADOConnection.runTask(getCurrDs(), lineOperationAnalysisService, "selectList", List.class, date,equipmentNames);
        ReportGenerationVO reportGenerationVO = new ReportGenerationVO();
        reportGenerationVO.setLineTotal(selectList.stream().filter(i->i.getLineTotal()!=null&&i.getLineTotal()!=0).mapToInt(ReportGenerationVO::getLineTotal).sum());
        reportGenerationVO.setLineCut(selectList.stream().filter(i->i.getLineCut()!=null&&i.getLineCut()!=0).mapToInt(ReportGenerationVO::getLineCut).sum());
        reportGenerationVO.setLineNonCut(selectList.stream().filter(i->i.getLineNonCut()!=null&&i.getLineNonCut()!=0).mapToInt(ReportGenerationVO::getLineNonCut).sum());
        reportGenerationVO.setDefectNew(selectList.stream().filter(i->i.getDefectNew()!=null&&i.getDefectNew()!=0).mapToInt(ReportGenerationVO::getDefectNew).sum());
        reportGenerationVO.setDefect00(selectList.stream().filter(i->i.getDefect00()!=null&&i.getDefect00()!=0).mapToInt(ReportGenerationVO::getDefect00).sum());
        reportGenerationVO.setDefect01(selectList.stream().filter(i->i.getDefect01()!=null &&i.getDefect01()!=0).mapToInt(ReportGenerationVO::getDefect01).sum());
        reportGenerationVO.setDefect01New(selectList.stream().filter(i->i.getDefect01New()!=null &&i.getDefect01New()!=0).mapToInt(ReportGenerationVO::getDefect01New).sum());
        reportGenerationVO.setDefect00New(selectList.stream().filter(i->i.getDefect00New()!=null &&i.getDefect00New()!=0).mapToInt(ReportGenerationVO::getDefect00New).sum());
        reportGenerationVO.setDefectTotal(selectList.stream().filter(i->i.getDefectTotal()!=null &&i.getDefectTotal()!=0).mapToInt(ReportGenerationVO::getDefectTotal).sum());
        reportGenerationVO.setDefectLast00(selectList.stream().filter(i->i.getDefectLast00()!=null &&i.getDefectLast00()!=0).mapToInt(ReportGenerationVO::getDefectLast00).sum());
        reportGenerationVO.setDefectLast01(selectList.stream().filter(i->i.getDefectLast01()!=null &&i.getDefectLast01()!=0).mapToInt(ReportGenerationVO::getDefectLast01).sum());
        reportGenerationVO.setDefectTotalLast(selectList.stream().filter(i->i.getDefectTotalLast()!=null &&i.getDefectTotalLast()!=0).mapToInt(ReportGenerationVO::getDefectTotalLast).sum());
        reportGenerationVO.setDefectThis01(selectList.stream().filter(i->i.getDefectThis01()!=null &&i.getDefectThis01()!=0).mapToInt(ReportGenerationVO::getDefectThis01).sum());
        reportGenerationVO.setDefectThis00(selectList.stream().filter(i->i.getDefectThis00()!=null &&i.getDefectThis00()!=0).mapToInt(ReportGenerationVO::getDefectThis00).sum());
        reportGenerationVO.setDefectTotalThis(selectList.stream().filter(i->i.getDefectTotalThis()!=null &&i.getDefectTotalThis()!=0).mapToInt(ReportGenerationVO::getDefectTotalThis).sum());
        reportGenerationVO.setTripTimes(selectList.stream().filter(i->i.getTripTimes()!=null &&i.getTripTimes()!=0).mapToInt(ReportGenerationVO::getTripTimes).sum());
        reportGenerationVO.setEquipmentName("总计");
        selectList.add(reportGenerationVO);
        ArrayList<LineOperationReportExcel> exportList = new ArrayList<>();
        for (ReportGenerationVO reportGeneration : selectList) {
            LineOperationReportExcel lineOperationReportExcel = lineOperationConverter.EntityToExcel(reportGeneration);
            exportList.add(lineOperationReportExcel);
        }
        HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(StyleUtills.getHeadStyle(),StyleUtills.getContentStyle());
        WriteSheet sheet = EasyExcel.writerSheet(0,"线路运行分析报告").head(LineOperationReportExcel.class).build();
        ExcelWriter writer = EasyExcel.write(response.getOutputStream())
                .withTemplate(classPathResource.getInputStream())
                .registerWriteHandler( new LongestMatchColumnWidthStyleStrategy())
                .registerWriteHandler( horizontalCellStyleStrategy)
                .needHead(true)
                .build();
        writer.write(exportList,sheet);
        writer.finish();
    }
}
